<template>
    <div>
       <h3>分类参数页面</h3>
       <Breadcrumb :breadcrumba="breadcrumba" :breadcrumbb="breadcrumbb"></Breadcrumb>
       <el-card>
           <el-tag type="warning"><i class="el-icon-warning"></i> 注意：只允许为第三级标签设置相关参数！</el-tag>
            <div>
                选择商品分类：
                <!-- props 联级选择器的 配置 写到这里 可以看下文档-->
                <el-cascader
                    v-model="selectedKeys"
                    :options="parentCatList"
                    @change="handleChange"
                    :props="{ expandTrigger: 'hover',
                   
                    value:cascaderProps.value,
                    label:cascaderProps.label,
                    children:cascaderProps.children}"
                    clearable
                    size="medium"
                    ></el-cascader>
            </div>
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many" >
                    <el-button type="primary" :disabled="selectedKeys.length === 0" @click="addAttributes">添加参数</el-button>

                    <el-table
                    :data="manyAttributesList"
                    style="width: 100%">
                    <el-table-column type="expand">
                    <template slot-scope="scope">
                    
                        <el-tag v-for="(item,i) of scope.row.attr_vals" :key="i" closable :disable-transitions="false"
                        @close="handleClose(scope.row,item)">{{item}}</el-tag>
                        <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                       <!-- <div>{{props.row.attr_vals}}</div> -->
                    </template>
                    </el-table-column>
                    <el-table-column
                    type="index"
                    width="50"
                    label="序号">
                    </el-table-column>
                    <el-table-column
                    label="参数名称"
                    prop="attr_name">
                    </el-table-column>
                    <el-table-column
                    label="操作"
                    >
                        <template slot-scope="scope">
                            <el-button @click="change(scope.row)" type="primary" icon="el-icon-edit">修改</el-button>
                            <el-button @click="del(scope.row)" type="danger" icon="el-icon-delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                     <el-button type="primary" :disabled="selectedKeys.length === 0" @click="addAttributes">添加属性</el-button>

                     <el-table
                    :data="onlyAttributesList"
                    style="width: 100%"
                    height="500">
                    <el-table-column type="expand">
                    <template slot-scope="scope">
                    
                        <el-tag v-for="(item,i) of scope.row.attr_vals" :key="i" closable :disable-transitions="false"
                        @close="handleClose(scope.row,item)">{{item}}</el-tag>
                        <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="$event.target.blur"
                        @blur="handleInputConfirm(scope.row)"
                        >
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                       <!-- <div>{{props.row.attr_vals}}</div> -->
                    </template>
                    </el-table-column>
                    <el-table-column
                    type="index"
                    width="50"
                    label="序号">
                    </el-table-column>
                    <el-table-column
                    label="属性名称"
                    prop="attr_name">
                    </el-table-column>
                    <el-table-column
                    label="操作"
                    >
                        <template slot-scope="scope">
                            <el-button @click="change(scope.row)" type="primary" icon="el-icon-edit">修改</el-button>
                            <el-button @click="del(scope.row)" type="danger" icon="el-icon-delete">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                </el-tab-pane>
            </el-tabs>
       </el-card>

       <!-- 弹出框 两个 添加按钮用一个弹出框 -->
       <el-dialog
        :title="activeName === 'many' ? '添加参数' : '添加属性'"
        :visible.sync="addAttributesVisible"
        width="40%"
        @close="aa">
        <div>
            <el-form :model="paramsForm" :rules="paramsRules" ref="paramsForm" label-width="100px">
                <el-form-item :label="activeName === 'many' ? '参数名称' : '属性名称'" prop="attr_name">
                    <el-input v-model="paramsForm.attr_name"></el-input>
                </el-form-item>

                <el-form-item v-if="activeName === 'many'">
                    <el-input v-model="paramsForm.attr_vals" placeholder="填写值得选项用，分隔"></el-input>
                </el-form-item>
            </el-form>
        </div>
        <!-- <div v-else>
            <el-form :model="paramsForm" :rules="paramsRules" ref="ruleForm" label-width="100px">
                <el-form-item label="属性名称" prop="paramsname">
                    <el-input v-model="paramsForm.paramsname"></el-input>
                </el-form-item>
            </el-form>
        </div> -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="addAttributesVisible = false">取 消</el-button>
            <el-button type="primary" @click="editCategoriesAttributes">确 定</el-button>
        </span>
        </el-dialog>

        <!-- 弹出框 修改 -->
        <el-dialog
        title="修改参数/属性"
        :visible.sync="changeAttributesVisible"
        width="40%"
        @close="changeClose">
        <div>
            <el-form :model="changeInfo" :rules="paramsRules" ref="changeInfoForm" label-width="100px">
                <el-form-item label="新属性名字" prop="attr_name">
                    <el-input v-model="changeInfo.attr_name"></el-input>
                </el-form-item>

                <el-form-item v-if="activeName === 'many'">
                    <el-input v-model="changeInfo.attr_vals" placeholder="填写值得选项用，分隔"></el-input>
                </el-form-item>
            </el-form>
        </div>
       
        <span slot="footer" class="dialog-footer">
            <el-button @click="changeAttributesVisible = false">取 消</el-button>
            <el-button type="primary" @click="editCategoriesAttributesById">确 定</el-button>
        </span>
        </el-dialog>

    </div>
</template>

<script>
import Breadcrumb from "../../components/Breadcrumb"
import {getGoodsList,getCategoriesAttributes,editCategoriesAttributes,
delCategoriesAttributes,getCategoriesAttributesById,editCategoriesAttributesById} from "../../api/goods"
    export default {
        components:{
            Breadcrumb
        },
        data(){
            return{
                breadcrumba:'',
                breadcrumbb:'',
                // 指定级联 选择器 的配置对象  分别是 值 名称 父子通过什么进行嵌套的
                cascaderProps:{
                    value:'cat_id',
                    label:'cat_name',
                    children:'children'
                },
                // 选中的父级分类的 id 数组
                selectedKeys:[],
                parentCatList:[],
                activeName: 'many',
                manyAttributesList:[],
                onlyAttributesList:[],
                addAttributesVisible:false,
                paramsForm:{
                    attr_name:"",
                    attr_vals:""
                },
                paramsRules:{
                   attr_name: [
                        { required: true, message: '请输入参数名称', trigger: 'blur' },
                        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                    ]
                },
                changeInfo:{
                    
                },
                changeAttributesVisible:false,
                // inputVisible:false,
                // inputValue:''
            }
        },
        created(){
            this.breadcrumba=sessionStorage.getItem('breadcrumba')
            this.breadcrumbb=sessionStorage.getItem('breadcrumbb')
            this.getParentCatList()
        },
        methods:{
            async handleChange() {
                // 用 输出出的数组长度进行判断 是三的话就是选取了最后一级
                // 如果不是三的话 需要进行清空 将 selectedKeys 设为 空
                console.log(this.selectedKeys,"改变之后数组的值");
                let id = this.selectedKeys[this.selectedKeys.length - 1 ]
                let {data:res} = await getCategoriesAttributes({id,sel:{sel:[this.activeName]}})

                // ***赋值前  对 结果进行循环 把每一项的attr_vals 变成 数组 在重新赋值给它自己
                // ************************//
                res.data.forEach(item =>{
                    // 进行判断 用三元 直接赋值的话 会有空的标签被渲染出来
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []

                    // ******** 自定义属性 防止 点击一个按钮 就都出现了 给每个 自定义一个属性 用这个属性 来进行判断隐藏 和 双向数据的绑定*******//
                    item.inputVisible = false
                    item.inputValue = ''
                })
                
                if(this.activeName === 'many' ){
                    this.manyAttributesList = res.data
                }else{
                    this.onlyAttributesList = res.data
                }
                // this.AttributesList = res.data
                console.log(res,"获取参数列表的返回值");
            },
            async getParentCatList(){
                let {data:res} = await getGoodsList()
                if(res.meta.status !== 200){
                    return this.$message,error("获取父级数据列表错误！")
                }
                // console.log(res,"获取的是父级二级的列表");
                this.parentCatList = res.data
            },
            handleClick(){
                console.log(this.activeName);
                if(this.selectedKeys.length === 3){
                    this.handleChange()
                }else{
                    this.$message.error('请选择对应的商品分类！')
                }
                
            },
            async change(row){
                console.log(row,"修改的");
                this.changeAttributesVisible = true
                let {data:res} = await getCategoriesAttributesById({id:row.cat_id,attrid:row.attr_id,attr_sel:{attr_sel:this.activeName}})
                if(res.meta.status !== 200){
                    return this.$message.error('获取失败！')
                }
                this.changeInfo = res.data
                // this.changeInfo.attr_name = res.data.attr_name
                // this.changeInfo.attr_vals = res.data.attr_vals
                console.log(this.changeInfo,"修改返回来的值");
            },
            // 删除参数
            del(row){
                    this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async () => {
                        let {data:res} = await delCategoriesAttributes({id:row.cat_id,attrid:row.attr_id})
                        if(res.meta.status !== 200){
                            return this.$message.error('删除参数失败')
                        }
                        this.$message.success('删除参数成功！')
                        this.handleChange()
                        console.log(res,"删除之后返回的值");
                    }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });          
                    });
                // console.log(row.cat_id,row.attr_id,"删除的");  
            },
            // 关闭弹出框 执行 清空
            aa(){
                // console.log(1);
                this.paramsForm.attr_name = ''
                this.paramsForm.attr_vals = ''
            },
            // 添加 参数 和 属性
            addAttributes(){
                this.addAttributesVisible = true
            },
            // 添加参数 的 form表单 应该 先进行 表单验证 验证没问题 再执行
            //  submitForm(formName) {
            //     this.$refs[formName].validate((valid) => {
            //       if (valid) {
            //         alert('submit!');
            //       } else {
            //         console.log('error submit!!');
            //         return false;
            //       }
            //     });
            //   },

            // 另一种 方法 this.$refs.addFormRef.validate(valid => {
            //     if(!valid) return 
            //     ...
            //  })
            async editCategoriesAttributes(){
                console.log(this.selectedKeys[2],this.paramsForm.attr_name,this.activeName,this.paramsForm.attr_vals,"dddd");
                let {data:res} = await editCategoriesAttributes(
                    this.selectedKeys[2],{
                        attr_name:this.paramsForm.attr_name,
                        attr_sel:this.activeName,
                        attr_vals:this.paramsForm.attr_vals
                        })
                if(res.meta.status !== 201){
                    return this.$message.error("添加参数失败！")
                }
                this.$message.success("添加参数成功！")
                this.addAttributesVisible = false
                this.paramsForm.attr_name = ""
                this.paramsForm.attr_vals = ""
                this.handleChange()
                console.log(res,"添加参数之后的返回值"); 
            },
            async editCategoriesAttributesById(){
                let {data:res} = await editCategoriesAttributesById(
                    {id:this.changeInfo.cat_id,attrId:this.changeInfo.attr_id,
                    info:{attr_name:this.changeInfo.attr_name,attr_sel:this.changeInfo.attr_sel,attr_vals:this.changeInfo.attr_vals}})
                if(res.meta.status !== 200){
                    return this.$message.error('修改参数失败！')
                }
                this.$message.success('修改参数成功！')
                this.changeAttributesVisible = false
                this.handleChange()
                console.log(res,"编辑修改");
            },
            changeClose(){
                this.changeInfo = {}
            },
            // 添加标签的 按钮方法
            async handleInputConfirm(row) {
                console.log(row,this.inputValue,"添加标签的值");
                row.inputVisible = false;

                if(!row.inputValue){
                    return this.$message.error('标签不能为空！')
                }
                
                

                let newString = ''
                if(row.attr_vals.length === 0){
                    newString = row.inputValue
                }else{
                    // 直接push进 这个数组 就行 页面就会增加！！！！！！！！！！
                    for (var item of row.attr_vals){
                        if(item === row.inputValue){
                            row.inputValue = ''
                            return this.$message.error('不要添加重复的标签！')
                        }
                    }
                    
                    row.attr_vals.push(row.inputValue.trim())
                    // newString = row.attr_vals.join(',') + ',' + row.inputValue
                    newString = row.attr_vals.join(',')
                }
                

                let {data:res} = await editCategoriesAttributesById(
                    {id:row.cat_id,attrId:row.attr_id,
                    info:{attr_name:row.attr_name,attr_sel:this.activeName,attr_vals:newString}})
                if(res.meta.status !== 200){
                    return this.$message.error('添加标签失败！')
                }
                this.$message.success("添加标签成功！")
                row.inputValue = ''
                // this.handleChange()
                console.log(res,"添加一个标签之后的返回值！");
                // let inputValue = this.inputValue;
                // if (inputValue) {
                // this.dynamicTags.push(inputValue);
                // }
                // this.inputVisible = false;
                // this.inputValue = '';
            },
            showInput(row) {
                row.inputVisible = true;
                // 通过 这行代码 可以 直接获取 input框的 焦点
                // $nextTick 函数方法 的作用  当页面上元素被重新渲染之后 才会执行回调函数中的代码 当页面上的元素 重新渲染完成之后 执行
                // refs  引用
                this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            async handleClose(row,tag) {
                // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
                let newArray = []
                console.log(row,tag);
                // 箭头函数 不加{} 直接返回 筛选之后的值
                row.attr_vals = row.attr_vals.filter(item => item !== tag)
                newArray = row.attr_vals.filter(item => item !== tag)
                let newString = newArray.join(',')
                console.log(newString,"新的数组");

                let {data:res} = await editCategoriesAttributesById(
                    {id:row.cat_id,attrId:row.attr_id,
                    info:{attr_name:row.attr_name,attr_sel:this.activeName,attr_vals:newString}})
                if(res.meta.status !== 200){
                    return this.$message,error('删除标签失败！')
                }
                this.$message.success("删除标签成功！")

                // row = res.data
                // this.handleChange()
                console.log(res,"删除一个标签后的返回值！！");
            },

        }
    }
</script>

<style scoped>
    .el-card{
        margin-top: 10px;
    }
    .el-icon-warning{
        font-size: 16px;
        margin-right: 6px;
    }
    .el-cascader{
        width: 400px;
        margin: 15px 0;
    }
    .el-tag{
        margin: 0 5px;
    }
    .el-tag + .el-tag {
    margin-left: 10px;
    }
    .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
    }
</style>